package com.lowcode.platform.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lowcode.platform.entity.Permission;
import com.lowcode.platform.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PermissionService extends ServiceImpl<PermissionMapper, Permission> {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    /**
     * 获取权限树（中文字段: permission_code -> code）
     */
    public List<Permission> getPermissionTree() {
        List<Permission> allPermissions = permissionMapper.getPermissionTree();
        // 使用释意为code字段
        return buildTree(allPermissions);
    }
    
    /**
     * 构建不层程树结构
     */
    private List<Permission> buildTree(List<Permission> allPermissions) {
        Map<Long, Permission> permissionMap = new HashMap<>();
        List<Permission> rootList = new ArrayList<>();
        
        // 先将所有权限存入一个map
        for (Permission permission : allPermissions) {
            permissionMap.put(permission.getId(), permission);
            // 处理层级关系
            if (permission.getParentId() == null || permission.getParentId() == 0) {
                rootList.add(permission);
            }
        }
        
        // 构建不层结构
        for (Permission permission : allPermissions) {
            if (permission.getParentId() != null && permission.getParentId() != 0) {
                Permission parent = permissionMap.get(permission.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(permission);
                }
            }
        }
        
        return rootList;
    }
}
